<template>
  <div class="business_report_agent agent" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other" :query="query" @isFold="isShowFold"></date-time>
            <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="skill">
                  <!-- <span class="ski">{{$t('public.agent')}} :</span>
                  <el-select size="mini" v-model.trim="selectedAgentList" multiple filterable :placeholder="$t('public.pickAgent')">
                    <el-option v-for="item in agentOptions"
                               :label="item.label"
                               :value="item.value"
                               :key="item.value"></el-option></el-select>
                    <el-checkbox v-model.trim="query.includeSubordinate">{{$t('public.includeSubordinate')}}</el-checkbox> -->
                  <div class="wrap_conti">
                    <span class="chan_ag">{{$t('report.chooseAgent')}}:</span>
                    <el-radio-group v-model="radio3"
                                    size = "mini"
                                    @change = "changeAgent">
                      <div>
                        <el-radio :label="1">{{$t('public.checkAll')}}</el-radio></div>
                      <div :class="[{wrap_agents: wrapAgents}, 'skill']">
                        <el-radio :label="2">{{$t('report.accordAgentChoose')}}</el-radio>
                        <!-- <el-select v-model="selectedAgentList"
                                      multiple
                                      filterable
                                      :disabled = "radio3 !== 2"
                                      size="mini"
                                      @change="agentsChange"
                                      :placeholder="$t('report.pleChoseAgent')">
                            <el-option
                              v-for="item in agentOptions"
                              :label="item.label"
                              :value="item.value"
                              :key="item.value">
                            </el-option>
                          </el-select> -->
                          <m7Select class="el-select" filterable multiple :options="selectAgents" :disabled = "radio3 !== 2" v-model="selectedAgentList"></m7Select>
                        <el-checkbox :disabled = "radio3 !== 2"
                                      v-model.trim="query.includeSubordinate">
                          {{$t('public.includeSubordinate')}}</el-checkbox></div>
                      <div class="skill dept">
                        <el-radio :label="4">{{$t('report.accordDeptChoose')}} </el-radio>
                        <el-select size="mini"
                                    v-model.trim="currentdept"
                                    :placeholder="$t('report.deptNaSea')"
                                    multiple
                                    :disabled = "radio3 !== 4"
                                    filterable
                                    @change = "changeDept">
                          <el-option v-for="item in depts"
                                      :label="item.name"
                                      :value="item.treePath"
                                      :key="item._id"></el-option>
                        </el-select>
                        <el-checkbox :disabled = "radio3 !== 4"
                                      v-model.trim="isShowDeptAgent"
                                      @change = changeShowDept>
                            {{$t('report.isShowDeptAgent')}}</el-checkbox></div>
                    </el-radio-group>
                  </div>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="title"></affix>
    </div>
    <div :id="id">
      <el-row class="ichars">
        <highcharts :options="highchartsOptions"></highcharts>
        <div class="notes">
          <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
          <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
        </div>
      </el-row>
      <div class="tab agent_table deal_margin">
        <div class="export">
          <el-button class="primary_btn fr" v-if="!configHeaderBool" v-on:click.stop="config">{{$t('report.setHeaderConfig')}}</el-button>

          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            @click.stop="exportXls"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            @click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
        </div>
        <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
              </template>
              <div>
                {{$t('report.creatBusinessNumber')}} <br>
                {{$t('report.receiveBusinessNumber')}} <br>
                {{$t('report.dealBusiness')}} <br>
                {{$t('report.averDealTime')}} <br>
                {{$t('report.distributionBusiNum')}} <br>
                {{$t('report.distributedBusiNum')}} <br>
                {{$t('report.averWaitTimeAgent')}}
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <checkbox-table :data="tableData" :sum="totalData" :config="headOptions.Config" @tellme = "reducteDate"> </checkbox-table>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
    <header-option v-show="isShow" :show="isShow" :option="headOptionsShow" type="business_report_agent" v-on:close="close"></header-option>
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../ui-modules/unfold/index.vue'
  import dateTime from '../base/datetime.vue'
  import reportTable from '../base/reportTable.vue'
  import checkboxTable from '../base/checkboxTable.vue'
  import { deepClone, getFormatTimeBySecond, optionTimeTypeCheck } from '@/utils/m7Utils.js'
  import { exportReportPdf, checkTime, searchTime, colorConfigArr, headOptionsToXlsxHeaders } from '@/utils/reportUtils.js'
  import headerOption from '../base/headerOption.vue'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  export default {
    name: 'business_report_agent',
    data () {
      return {
        wrapAgents: false, // 是防止座席数据量展示太大设置样式index -1
        currentdept: [], // 选择部门绑定得id值
        selectedAgentListClone: [], // 是否展示座席得复制版
        depts: [], // 部门
        isShowDeptAgent: false, // 是否展示部门下的座席
        radio3: 1, // 各座席工作量下面选择切换绑定得值
        isFold: false,  // 是否展示搜索条件
        noDealDate: [], // 表格展示内容的集合 用来渲染图表 合计
        id: 'business_report_agent', // 查询传的id
        title: this.$t('report.businessReportAgent'),
        loading: false,
        dialogVisible: false, // 导出pdf弹窗开关
        query: {includeSubordinate: false}, // 查询条件
        headOptionsShow: {}, // 配置表头传入的对象
        isShow: false, // 配置表头开关
        selectedAgentList: [], // 座席选择绑定的值
        agentOptions: [], // 座席缓存的信息里面有名字加工号还有座席id
        serverData: [], // 返回的data 数据
        headOptions: { Config: [], data: [] }, // 表头数据
        highchartsDefaultOptions: {
          chart: { type: 'column', animation: false },
          colors: colorConfigArr,
          xAxis: {
            categories: [],
            title: {
              enabled: true,
              text: '',
              style: { fontWeight: 'normal' }
            }
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: { text: '' },
            showEmpty: false
          },
          title: { text: this.$t('report.businessReportAgent') },
          legend: { align: 'center', verticalAlign: 'top', y: 30 },
          tooltip: {
            pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}{point.valueSuffix}</b><br/>',
            shared: true
          },
          credits: { enabled: false },
          series: []
        }
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      reportTable,
      checkboxTable,
      headerOption
    },
    computed: {
      // 判断是否为过滤座席 返回座席下拉数据
      selectAgents () {
        if (this.$store.getters.userHidden === 'yes') {
          return this.$store.getters.filterStopAgents && this.$store.getters.filterStopAgents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id, deptId: agent.deptId ? agent.deptId : '' }))
        }
        return  this.agentOptions
      },
      // 是否展示配置表头
      configHeaderBool () {
        return this.$store.state.report.setConfigHeaderBool
      },
      tableData () {
        return this.getTableData(this.serverData, this.headOptions)
      },
      totalData () {
        return this.getTotalData(this.noDealDate, this.headOptions)
      },
      highchartsOptions () {
        let options = deepClone(this.highchartsDefaultOptions)
        if (!this.noDealDate || this.noDealDate.length === 0) {
          return options
        }

        let headerConfig = this.headOptions.Config || []
        let datas = this.noDealDate
        let categoriesArray = []
        let seriesArray = []

        headerConfig.forEach(item => {
          if (!item.show) {
            return
          }
          if (item.name === 'agent') {
            return
          }
          let serie = { name: item.displayname, data: [], valueName: item.name }
          if (item.name === 'processTimeAvg' || item.name === 'waitTimeAvg') {
            serie.tooltip = { valueSuffix: 's' }
          }
          seriesArray.push(serie)
        })

        for (let i = 0; i < datas.length; i++) {
          categoriesArray.push(this.getAgentName(datas[i].agent) || datas[i].agent)
          for (let j = 0; j < seriesArray.length; j++) {
            seriesArray[j].data.push(datas[i][seriesArray[j].valueName])
          }
        }

        options.xAxis.categories = categoriesArray
        options.series = seriesArray

        return options
      }
    },
    methods: {
      // 座席组件改变得事件
      agentsChange () {
        if (this.wrapAgents) {
          this.wrapAgents = false
        }
      },
      // 各座席量选择切换
      changeAgent () {
        this.selectedAgentList = []
        this.selectedAgentListClone = []
        this.currentdept = []
        this.isShowAgent = false
        this.isShowDeptAgent = false
        this.query.includeSubordinate = false
        this.wrapAgents = false
      },
      // 部门切换执行方法，筛选座席
      changeDept (deptTreePaths) {
        this.selectedAgentList = []
        this.selectedAgentListClone = []
        let deptIds = [] // 创建部门id数组集
        if (deptTreePaths.length !== 0) {
          for (let i = 0; i < deptTreePaths.length; i++) {
            if (deptTreePaths[i] === 'noDept') {
              deptIds.push('')
            } else {
              let deptIdArr = deptTreePaths[i].split('/')
              let deptId = deptIdArr[deptIdArr.length - 2] // 当前部门id
              deptIds.push(deptId) // 像部门数组中添加当前部门id
              for (let j = 0; j < this.depts.length; j++) {
                let isDeptIdArr = this.depts[j].treePath.split(deptId + '/')[1] // 判断当前部门下面得部门是否存在
                if (isDeptIdArr) {
                  deptIds = deptIds.concat(isDeptIdArr.split('/').filter(item => item))
                }
              }
            }
          }
          deptIds = Array.from(new Set(deptIds)) // 部门id去重
          let cloneAgentsArr = []
          cloneAgentsArr = this.agentOptions.filter(item => { // 过滤座席信息得部门是否在部门数组里，是则返回
            return deptIds.includes(item.deptId)
          })
          cloneAgentsArr.map(item => {
            this.selectedAgentListClone.push(item.value)
          })
          console.log(this.selectedAgentListClone)
          if (this.isShowDeptAgent) {
            this.selectedAgentList = this.selectedAgentListClone
          }
        }
      },
      // 是否展示部门下的座席
      changeShowDept (cur) {
        if (cur) {
          this.wrapAgents = false
          this.selectedAgentList = this.selectedAgentListClone
        } else {
          this.selectedAgentList = []
          this.wrapAgents = true
        }
      },
      getTableData (serverData, headOptions, isExport) {
        if (!serverData || serverData.length === 0) {
          return []
        }

        let data = deepClone(serverData)
        data.forEach(item => {
          if (isExport) {
            var {displayName, exten} = this.getAgentDisplayNameAndExten(item.agent)
            item.agent = displayName
            item.agentExten = exten
          } else {
            item.agent = this.getAgentName(item.agent) || item.agent
          }

          headOptions.Config.forEach((option, index) => {
            if (option.timeType && option.timeType === 'hhmmss') {
              item[option.name] = getFormatTimeBySecond(item[option.name])
            } else if (option.timeType && option.timeType === 'second') {
              item[option.name] = item[option.name] + 's'
            }
          })
        })

        return data
      },
      getTotalData (noDealDate, headOptions) {
        if (!noDealDate || noDealDate.length === 0) {
          return [{agent: this.$t('report.total')}]
        }

        let headerConfig = headOptions.Config || []
        let datas = noDealDate
        let total = {
          agent: this.$t('report.total'),
          processTimeCount: 0,
          waitTimeCount: 0,
          pickCount: 0
        }

        for (let i = 0; i < headerConfig.length; i++) {
          for (let j = 0; j < datas.length; j++) {
            if (!isNaN(datas[j][headerConfig[i].name])) {
              if ((headerConfig[i].name in total) === false) {
                total[headerConfig[i].name] = 0
              }
              total[headerConfig[i].name] += datas[j][headerConfig[i].name]
            }

            if (headerConfig[i].name === 'processTimeAvg') {
              total.processTimeCount += datas[j]['processTimeCount']
            } else if (headerConfig[i].name === 'waitTimeAvg') {
              total.waitTimeCount += datas[j]['waitTimeCount']
              total.pickCount += datas[j]['pickCount']
            }
          }
        }

        // 平均处理时长
        total.processTimeAvg = total.process > 0 ? Math.round(total.processTimeCount / total.process) : 0
        // total.processTimeAvg = getFormatTimeBySecond(total.processTimeAvg)
        // 平均等待时长
        total.waitTimeAvg = total.pick > 0 ? Math.round(total.waitTimeCount / total.pick) : 0
        // total.waitTimeAvg = getFormatTimeBySecond(total.waitTimeAvg)
        headOptions.Config.forEach((option, index) => {
          if (option.timeType && option.timeType === 'hhmmss') {
            total[option.name] = getFormatTimeBySecond(total[option.name])
          } else if (option.timeType && option.timeType === 'second') {
            total[option.name] = total[option.name] + 's'
          }
        })
        return [total]
      },
      isShowFold (bool) {
        this.isFold = bool
      },
      reducteDate (data) {
        let dealDate = []
        data.map(item => {
          this.serverData.map(col => {
            if (item._id === col._id) {
              dealDate.push(col)
            }
          })
        })
        this.noDealDate = dealDate
      },
      getAgentName (id) {
        let agent = this.$store.getters.agents[id]
        let getAgent = agent ? agent.displayName + '(' + agent.exten + ')' : ''
        return getAgent
      },
      getAgentDisplayNameAndExten (id) {
        let agent = this.$store.getters.agents[id]
        return {
          displayName: agent ? agent.displayName : '',
          exten: agent ? agent.exten : ''
        }
      },
      getSearchQueryData () {
        let data = {
          reportType: this.id,
          account: this.$store.state.session.user.account,
          query: { reportType: this.id },
          user: {
            type: this.$store.state.session.user.type,
            moduleUsers: this.$store.state.session.user.moduleUsers
          }
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other') {
          // 校验类型与时间
          let message = checkTime(query.StartTime, query.EndTime, false, true)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
          let StartTimeStr = query.StartTime.replace(/-/g, '')
          query.StartTime = StartTimeStr
          let EndTimeStr = query.EndTime.replace(/-/g, '')
          query.EndTime = EndTimeStr
        }
        query.selectedAgentList = this.selectedAgentList.join(',')
        if (this.currentdept.length !== 0 && this.selectedAgentListClone.length === 0) {
          query.selectedAgentList = '000000'
        } else if (this.selectedAgentListClone.length > 0) {
          query.selectedAgentList = this.selectedAgentListClone.join(',')
        }
        data.query = Object.assign({}, data.query, query)
        return data
      },
      search () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        this.loading = true

        this.$store.dispatch('queryBusinessAgentReport', data).then((res) => {
          if (!res.success) {
            this.loading = false
            return
          }
          // 表头
          this.headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || this.headOptions)
          this.serverData = deepClone(res.data) || this.serverData
          this.noDealDate = deepClone(res.data)
          this.loading = false
        })
      },
      exportXlsx () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        this.loading = true

        this.$store.dispatch('queryBusinessAgentReport', data).then((res) => {
          if (!res.success) {
            this.loading = false
            return
          }
          this.loading = false
          var headOptions = optionTimeTypeCheck(deepClone(res.tableHeader) || [])
          var serverData = deepClone(res.data) || []
          var sum = []
          if (serverData.length !== 0) {
            sum = this.getTotalData(serverData, headOptions)
          }
          var tableData = this.getTableData(serverData, headOptions, true).concat(sum)
          var ConfigsTemp = []
          headOptions.Config && headOptions.Config.forEach(config => {
            ConfigsTemp.push(config)
            if (config.name === 'agent') {
              ConfigsTemp.push({
                show: config.show,
                displayname: '工号',
                name: 'agentExten'
              })
            }
          })
          headOptions.Config = ConfigsTemp

          var headers = headOptionsToXlsxHeaders(headOptions.Config)

          var dh = XlsxUtil.getDownloadHelper(headers, tableData)
          var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download('工单座席工作量报表' + timeStamp)
        })
      },
      exportXls () {
        let data = {
          Method: 'exportBusinessAgent',
          Query: { reportType: this.id, user: this.$store.state.session.user._id }
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other') {
          let message = checkTime(query.StartTime, query.EndTime, false, true) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
          let StartTimeStr = query.StartTime.replace(/-/g, '')
          query.StartTime = StartTimeStr
          let EndTimeStr = query.EndTime.replace(/-/g, '')
          query.EndTime = EndTimeStr
        }
        if (this.selectedAgentList.length > 0) {
          query.selectedAgentList = this.selectedAgentList.join(',')
        }
        data.Query = Object.assign({}, data.Query, query)
        this.$store.dispatch('exportBusinessAgentReport', data)
      },
      exportPdf () {
        this.dialogVisible = true
      },
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.businessReportAgent') + searchTime(this.query), id: this.id})
      },
      //   配置 表头
      config () {
        this.$store.dispatch('getReportTableHeader', 'business_report_agent').then((res) => {
          this.headOptionsShow = optionTimeTypeCheck(res)
          this.isShow = !this.isShow
        })
      },
      close (data) {
        this.isShow = false
        if (data === 'save') {
          this.search()
        }
      }
    },
    beforeMount () {
      // 获取部门缓存
      this.$store.dispatch('getCache', {type: 'depts'}).then((dept) => {
        this.depts = dept.filter(item => {
          return item.pId
        })
        this.depts.push({
          name: '未分配部门',
          treePath: 'noDept'
        })
      })
      this.$store.dispatch('getCache', { type: 'agents' }).then(agents => {
        this.agentOptions = agents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id, deptId: agent.deptId ? agent.deptId : '' }))
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .business_report_agent
    .search
      .wrap_conti
          margin 14px 0 0 0px
          .ski
            margin-right 26px
          .chan_ag
            float left
            margin-right 20px
          .el-radio
            margin-right 30px
          .dept
            .el-radio
              margin-right 42px
      .el-checkbox
        margin-left 16px
    .tab
      margin-bottom 20px
      .deploy
        .tip
          margin-left 40px
        .item
          cursor pointer
          &:hover
            color $c-main
    .top
      .sear
        margin-left 0
      .skill
        margin-top 16px
        .el-select
          width 366px
        .ski
          margin-right 16px
          display inline-block
          width 42px
    .deploy
      .tex
        margin-left 10px
    .el-col-1
      height 36px
      line-height 36px
</style>
